package top.someapp.applib.generator;

import java.math.BigDecimal;
import java.util.Random;
import top.someapp.applib.AppException;

/**
 * 骰子，随机数生成
 *
 * @author zwz
 * Created on 2019-06-09
 */
public class Dice {

    private static final Random random = new Random();
    private static final String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
    private static final String upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final String alphabetAndDigitals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private Dice() {
        // no need instance.
    }

    public static int nextInt(int max) {
        return random.nextInt(max);
    }

    public static int nextInt(int min, int max) {
        if (min >= max) {
            throw new AppException("min must less than max!");
        }
        return min + nextInt(max - min);
    }

    public static Number nextNumber(int max) {
        return new BigDecimal(nextInt(max));
    }

    public static Number nextNumber(int min, int max) {
        return new BigDecimal(nextInt(min, max));
    }

    public static boolean nextBoolean() {
        return nextInt(100) % 2 == 0;
    }

    /**
     * 随机产生一个小写字母
     *
     * @return 一个小写字母
     */
    public static char randomLetterLower() {
        return lowerCaseLetters.charAt(nextInt(26));
    }

    /**
     * 随机产生一个大写字母
     *
     * @return 一个大写字母
     */
    public static char randomLetterUpper() {
        return upperCaseLetters.charAt(nextInt(26));
    }

    public static String randomString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= length; i++) {
            sb.append(alphabetAndDigitals.charAt(nextInt(62)));
        }
        return sb.toString();
    }

    public static String randomHexString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= length; i++) {
            sb.append(alphabetAndDigitals.charAt(nextInt(16)));
        }
        return sb.toString();
    }

    public static <T> T randomEnum(T[] enumValues) {
        if (enumValues.length == 1) {
            return enumValues[0];
        }
        return enumValues[nextInt(enumValues.length)];
    }
}
